package test04;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class StringProcessor {

    public static void main(String[] args) {
        String sourceFile = "source.txt"; // 假设源文件名为source.txt
        try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String processedString = processString(line);
                System.out.println(processedString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String processString(String input) {
        // 查找并删除第一个双引号和最后一个双引号
        if (input.startsWith("\"") && input.endsWith("\"")) {
            input = input.substring(1, input.length() - 1);
        } else {
            throw new IllegalArgumentException("Input string does not have matching double quotes at the start and end.");
        }

        // 处理转义字符
        StringBuilder processed = new StringBuilder();
        boolean escape = false;
        for (int i = 0; i < input.length(); i++) {
            char current = input.charAt(i);
            if (escape) {
                // 处理转义字符，例如 \" 变成 "
                if (current == '"') {
                    processed.append('"');
                } else if (current == '\\') {
                    processed.append('\\');
                } else {
                    // 如果不是预期的转义字符，则保留原样（或者可以选择抛出异常）
                    processed.append('\\').append(current);
                }
                escape = false;
            } else if (current == '\\') {
                escape = true;
            } else {
                processed.append(current);
            }
        }

        // 如果字符串以转义字符结尾，则抛出异常（假设这是无效的）
        if (escape) {
            throw new IllegalArgumentException("Input string ends with an unescaped backslash.");
        }

        return processed.toString();
    }
}